package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"

	"github.com/astaxie/beego/orm"
)

type BxSoftware struct {
	Id              int    `orm:"column(id);auto"`
	MenberId        int    `orm:"column(menber_id)"`
	Name            string `orm:"column(name);size(50)"`
	SKey            string `orm:"column(s_key);size(255)"`
	HeartTime       int    `orm:"column(heart_time)"`
	Version         string `orm:"column(version);size(50)"`
	Notice          string `orm:"column(notice);size(255)"`
	StaticData      string `orm:"column(static_data);size(255)"`
	GiveTime        int    `orm:"column(give_time)"`
	GivePoint       int    `orm:"column(give_point)"`
	LoginType       int8   `orm:"column(login_type)"`
	UpdateData      string `orm:"column(update_data);size(50)"`
	UpdateType      int8   `orm:"column(update_type)"`
	TrialInterval   int    `orm:"column(trial_interval)"`
	TrialData       int    `orm:"column(trial_data)"`
	SoftwareState   int8   `orm:"column(software_state)"`
	BindingType     int8   `orm:"column(binding_type)"`
	BindingdelType  int8   `orm:"column(bindingdel_type)"`
	BindingdelTime  int    `orm:"column(bindingdel_time)"`
	BindingdelPoint int    `orm:"column(bindingdel_point)"`
	RestrictRegtime int    `orm:"column(restrict_regtime)"`
	RestrictRegnum  int    `orm:"column(restrict_regnum)"`
	Remote          string `orm:"column(remote)"`
	Encrypt         string `orm:"column(encrypt);size(50)"`
	DefinedEncrypt  string `orm:"column(defined_encrypt)"`
}

func (t *BxSoftware) TableName() string {
	return "bx_software"
}

func init() {
	orm.RegisterModel(new(BxSoftware))
}

// AddBxSoftware insert a new BxSoftware into database and returns
// last inserted Id on success.
func AddBxSoftware(m *BxSoftware) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetBxSoftwareById retrieves BxSoftware by Id. Returns error if
// Id doesn't exist
func GetBxSoftwareById(id int) (v *BxSoftware, err error) {
	o := orm.NewOrm()
	v = &BxSoftware{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllBxSoftware retrieves all BxSoftware matches certain condition. Returns empty list if
// no records exist
func GetAllBxSoftware(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(BxSoftware))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []BxSoftware
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateBxSoftware updates BxSoftware by Id and returns error if
// the record to be updated doesn't exist
func UpdateBxSoftwareById(m *BxSoftware) (err error) {
	o := orm.NewOrm()
	v := BxSoftware{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteBxSoftware deletes BxSoftware by Id and returns error if
// the record to be deleted doesn't exist
func DeleteBxSoftware(id int) (err error) {
	o := orm.NewOrm()
	v := BxSoftware{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&BxSoftware{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// machine_code='{$data['machine_code']}' AND regtime>'{$restrict_time}' AND software_id={$this->software['0']['id']}", '', '', '', 'COUNT(id)');
func CountReg(code string, rt int, id int) int {
	o := orm.NewOrm()
	cond := orm.NewCondition()
	cond1 := cond.And("machine_code", code).And("regtime", rt).And("software_id", id)
	qs := o.QueryTable("bx_software")
	cou, err := qs.SetCond(cond1).Count()
	if err != nil {
		return -1
	}
	return int(cou)
}
